<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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
 *
 *     http://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.
 */

var tests;

function assertTrue(msg, value) {
  if (!value) {
    throw "assertTrue() failed: " + msg;
  }
}

function assertFalse(msg, value) {
  if (value) {
    throw "assertFalse() failed: " + msg;
  }
}

function assertEquals(msg, a, b) {
  if (a != b) {
    throw "assertEquals() failed: " + msg +
        "\nExpected \"" + a + "\", was \"" + b + "\"";
  }
}

/**
 * Signals the server code that a test successfully finished.  This
 * method must be called to verify that a test completed successfully,
 * instead of simply failing to load.
 */
function finished() {
  alert("FINISHED");
}

/** Executes the test identifed by the testMethod URL parameter */
function executeTest() {
  var params = gadgets.util.getUrlParameters();
  var testMethod = params["testMethod"];
  if (!testMethod) {
    throw "No testMethod parameter found.";
  }

  // "all": run all the tests
  if ("all" == testMethod) {
    allTests();
  } else {
    // Show an alert for the test method name, identifying what test started.
    alert(testMethod);

    var testMethodFunction = tests[testMethod];
    if (!testMethodFunction) {
      throw "Test method " + testMethod + " not found.";
    }

    // Execute the test method
    testMethodFunction();
  }
}

function allTests() {
  for (var testMethod in tests) {
    alert(testMethod);
    tests[testMethod]();
  }
}

gadgets.util.registerOnLoadHandler(executeTest);
<commit_msg>Add serial execution of javascript tests<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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
 *
 *     http://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.
 */

var tests;

function assertTrue(msg, value) {
  if (!value) {
    throw "assertTrue() failed: " + msg;
  }
}

function assertFalse(msg, value) {
  if (value) {
    throw "assertFalse() failed: " + msg;
  }
}

function assertEquals(msg, a, b) {
  if (a != b) {
    throw "assertEquals() failed: " + msg +
        "\nExpected \"" + a + "\", was \"" + b + "\"";
  }
}

/**
 * Signals the server code that a test successfully finished.  This
 * method must be called to verify that a test completed successfully,
 * instead of simply failing to load.
 */

function finished() {
  alert("FINISHED");
  // After finishing run the next test..
  runOneTest();
}

/** Executes the test identifed by the testMethod URL parameter */
function executeTest() {
  var params = gadgets.util.getUrlParameters();
  var testMethod = params["testMethod"];
  if (!testMethod) {
    throw "No testMethod parameter found.";
  }

  // "all": run all the tests
  if ("all" == testMethod) {
    allTests();
  } else {
    // Show an alert for the test method name, identifying what test started.
    alert(testMethod);

    var testMethodFunction = tests[testMethod];
    if (!testMethodFunction) {
      throw "Test method " + testMethod + " not found.";
    }

    // Execute the test method
    testMethodFunction();
  }
}

var testFunctions = [];

function runOneTest() {
  var t = testFunctions.pop();
  if (t) {
    alert(t);
    tests[t]();
  }
}
function allTests() {
  // Collect the test names and iterate through them serially
  for (var testMethod in tests) {
    testFunctions.push(testMethod);
  }
  runOneTest();
}

gadgets.util.registerOnLoadHandler(executeTest);
<|endoftext|>


<commit_before>/**
 * User Input Settings tests.
 *
 * Site Kit by Google, Copyright 2021 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.
 */

/**
 * WordPress dependencies
 */
import { visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	activatePlugins,
	deactivateUtilityPlugins,
	resetSiteKit,
	setupSiteKit,
	useRequestInterception,
	enableFeature,
	pageWait,
	step,
	setSearchConsoleProperty,
} from '../utils';

describe( 'User Input Settings', () => {
	async function fillInInputSettings() {
		await step( 'select role', async () => {
			await page.waitForSelector( '.googlesitekit-user-input__question' );
			await expect( page ).toClick( '#role-owner_with_team' );
		} );

		await step( 'select post frequency', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#postFrequency-monthly' );
		} );

		await step( 'select goals', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#goals-publish_blog' );
			await expect( page ).toClick( '#goals-share_portfolio' );
		} );

		await step( 'select help needed', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#helpNeeded-retaining_visitors' );
			await expect( page ).toClick( '#helpNeeded-improving_performance' );
			await expect( page ).toClick( '#helpNeeded-help_better_rank' );
		} );

		await step( 'enter keywords', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toFill( '#searchTerms-keyword-0', 'One' );
			await expect( page ).toFill( '#searchTerms-keyword-1', 'Two' );
			await expect( page ).toFill( '#searchTerms-keyword-2', 'Three' );
		} );

		await step(
			'go to preview page',
			expect( page ).toClick( '.googlesitekit-user-input__buttons--next' )
		);

		await step(
			'wait for settings submission',
			Promise.all( [
				expect( page ).toClick(
					'.googlesitekit-user-input__buttons--next'
				),
				page.waitForNavigation(),
			] )
		);

		await step(
			'wait for success notification',
			page.waitForSelector( '#user-input-success' )
		);
	}

	beforeAll( async () => {
		await page.setRequestInterception( true );

		useRequestInterception( ( request ) => {
			const url = request.url();

			if (
				url.match(
					'/google-site-kit/v1/core/user/data/user-input-settings'
				)
			) {
				request.continue();
			} else if ( url.match( '/google-site-kit/v1/modules' ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await enableFeature( 'userInput' );
		await activatePlugins(
			'e2e-tests-proxy-setup',
			'e2e-tests-oauth-callback-plugin',
			'e2e-tests-user-input-settings-api-mock'
		);
		await setSearchConsoleProperty();
	} );

	afterEach( async () => {
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	it( 'should require new users to enter input settings after signing in', async () => {
		await step(
			'visit splash screen',
			visitAdminPage( 'admin.php', 'page=googlesitekit-splash' )
		);
		await step(
			'click on start setup button and wait for navigation',
			Promise.all( [
				expect( page ).toClick( '.googlesitekit-start-setup' ),
				page.waitForNavigation(),
			] )
		);

		await fillInInputSettings();
	} );

	it( 'should offer to enter input settings for existing users', async () => {
		await setupSiteKit();

		await step(
			'visit admin dashboard',
			visitAdminPage( 'admin.php', 'page=googlesitekit-dashboard' )
		);

		await step( 'click on CTA button and wait for navigation', async () => {
			await page.waitForSelector(
				'.googlesitekit-user-input__notification'
			);
			await Promise.all( [
				expect( page ).toClick( '.googlesitekit-notification__cta' ),
				page.waitForNavigation(),
			] );
		} );

		await fillInInputSettings();
	} );

	it( 'should let existing users enter input settings from the settings page', async () => {
		await setupSiteKit();

		await step( 'visit admin settings', async () => {
			await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
			await pageWait();
			await page.waitForSelector( '.mdc-tab-bar a.mdc-tab' );
			await expect( page ).toClick( 'a.mdc-tab', {
				text: /admin settings/i,
			} );
		} );

		await step( 'click on CTA button and wait for navigation', async () => {
			await page.waitForSelector(
				'.googlesitekit-user-input__notification'
			);
			await Promise.all( [
				expect( page ).toClick( '.googlesitekit-notification__cta' ),
				page.waitForNavigation(),
			] );
		} );

		await fillInInputSettings();
	} );
} );
<commit_msg>Conditionally skip user input E2E tests.<commit_after>/**
 * User Input Settings tests.
 *
 * Site Kit by Google, Copyright 2021 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.
 */

/**
 * WordPress dependencies
 */
import { visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	activatePlugins,
	deactivateUtilityPlugins,
	resetSiteKit,
	setupSiteKit,
	useRequestInterception,
	enableFeature,
	pageWait,
	step,
	setSearchConsoleProperty,
} from '../utils';

const wpConditionalDescribe = () => {
	// Only run for non WP 4.x versions
	if ( process.env.WP_VERSION?.[ 0 ] !== '4' ) {
		return describe;
	}
	return () => {
		it( 'is skipped for WP 4.x', () => {} );
	}; // no-op
};

wpConditionalDescribe()( 'User Input Settings', () => {
	async function fillInInputSettings() {
		await step( 'select role', async () => {
			await page.waitForSelector( '.googlesitekit-user-input__question' );
			await expect( page ).toClick( '#role-owner_with_team' );
		} );

		await step( 'select post frequency', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#postFrequency-monthly' );
		} );

		await step( 'select goals', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#goals-publish_blog' );
			await expect( page ).toClick( '#goals-share_portfolio' );
		} );

		await step( 'select help needed', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toClick( '#helpNeeded-retaining_visitors' );
			await expect( page ).toClick( '#helpNeeded-improving_performance' );
			await expect( page ).toClick( '#helpNeeded-help_better_rank' );
		} );

		await step( 'enter keywords', async () => {
			await expect( page ).toClick(
				'.googlesitekit-user-input__buttons--next'
			);
			await expect( page ).toFill( '#searchTerms-keyword-0', 'One' );
			await expect( page ).toFill( '#searchTerms-keyword-1', 'Two' );
			await expect( page ).toFill( '#searchTerms-keyword-2', 'Three' );
		} );

		await step(
			'go to preview page',
			expect( page ).toClick( '.googlesitekit-user-input__buttons--next' )
		);

		await step(
			'wait for settings submission',
			Promise.all( [
				expect( page ).toClick(
					'.googlesitekit-user-input__buttons--next'
				),
				page.waitForNavigation(),
			] )
		);

		await step(
			'wait for success notification',
			page.waitForSelector( '#user-input-success' )
		);
	}

	beforeAll( async () => {
		await page.setRequestInterception( true );

		useRequestInterception( ( request ) => {
			const url = request.url();

			if (
				url.match(
					'/google-site-kit/v1/core/user/data/user-input-settings'
				)
			) {
				request.continue();
			} else if ( url.match( '/google-site-kit/v1/modules' ) ) {
				request.respond( { status: 200 } );
			} else {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await enableFeature( 'userInput' );
		await activatePlugins(
			'e2e-tests-proxy-setup',
			'e2e-tests-oauth-callback-plugin',
			'e2e-tests-user-input-settings-api-mock'
		);
		await setSearchConsoleProperty();
	} );

	afterEach( async () => {
		await deactivateUtilityPlugins();
		await resetSiteKit();
	} );

	it( 'should require new users to enter input settings after signing in', async () => {
		await step(
			'visit splash screen',
			visitAdminPage( 'admin.php', 'page=googlesitekit-splash' )
		);
		await step(
			'click on start setup button and wait for navigation',
			Promise.all( [
				expect( page ).toClick( '.googlesitekit-start-setup' ),
				page.waitForNavigation(),
			] )
		);

		await fillInInputSettings();
	} );

	it( 'should offer to enter input settings for existing users', async () => {
		await setupSiteKit();

		await step(
			'visit admin dashboard',
			visitAdminPage( 'admin.php', 'page=googlesitekit-dashboard' )
		);

		await step( 'click on CTA button and wait for navigation', async () => {
			await page.waitForSelector(
				'.googlesitekit-user-input__notification'
			);
			await Promise.all( [
				expect( page ).toClick( '.googlesitekit-notification__cta' ),
				page.waitForNavigation(),
			] );
		} );

		await fillInInputSettings();
	} );

	it( 'should let existing users enter input settings from the settings page', async () => {
		await setupSiteKit();

		await step( 'visit admin settings', async () => {
			await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
			await pageWait();
			await page.waitForSelector( '.mdc-tab-bar a.mdc-tab' );
			await expect( page ).toClick( 'a.mdc-tab', {
				text: /admin settings/i,
			} );
		} );

		await step( 'click on CTA button and wait for navigation', async () => {
			await page.waitForSelector(
				'.googlesitekit-user-input__notification'
			);
			await Promise.all( [
				expect( page ).toClick( '.googlesitekit-notification__cta' ),
				page.waitForNavigation(),
			] );
		} );

		await fillInInputSettings();
	} );
} );
<|endoftext|>


<commit_before>/*
 * Copyright 2020 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 { percySnapshot } from '@percy/puppeteer';

/**
 * WordPress dependencies
 */
import {
  loginUser,
  switchUserToAdmin,
  visitAdminPage,
} from '@wordpress/e2e-test-utils';

describe('Get Started Story', () => {
  describe('Admin User', () => {
    it('should prefill post title and post content', async () => {
      await visitAdminPage(
        'post-new.php',
        'post_type=web-story&web-stories-demo=1'
      );

      await expect(page).toMatchElement('input[placeholder="Add title"]');
      await expect(page).toMatch(/Tips to make the most/i);
      await expect(page).toMatch(/to make the most of/i);

      await expect(page).toMatchElement('[data-testid="mediaElement"]');

      await percySnapshot(page, 'Get Started Story (Admin)');
    });
  });

  describe('Author User', () => {
    beforeAll(async () => {
      await loginUser('author', 'password');
    });

    afterAll(async () => {
      await switchUserToAdmin();
    });

    it('should prefill post title and post content', async () => {
      await visitAdminPage(
        'post-new.php',
        'post_type=web-story&web-stories-demo=1'
      );

      await expect(page).toMatchElement('input[placeholder="Add title"]');
      await expect(page).toMatch(/Tips to make the most/i);
      await expect(page).toMatch(/to make the most of/i);

      await expect(page).toMatchElement('[data-testid="mediaElement"]');

      await percySnapshot(page, 'Get Started Story (Author)');
    });
  });
});
<commit_msg>Await.<commit_after>/*
 * Copyright 2020 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 { percySnapshot } from '@percy/puppeteer';

/**
 * WordPress dependencies
 */
import {
  loginUser,
  switchUserToAdmin,
  visitAdminPage,
} from '@wordpress/e2e-test-utils';

describe('Get Started Story', () => {
  describe('Admin User', () => {
    it('should prefill post title and post content', async () => {
      await visitAdminPage(
        'post-new.php',
        'post_type=web-story&web-stories-demo=1'
      );

      await expect(page).toMatchElement('input[placeholder="Add title"]');
      await expect(page).toMatch(/Tips to make the most/i);
      await expect(page).toMatch(/to make the most of/i);

      await page.waitForSelector('[data-testid="mediaElement"]');

      await percySnapshot(page, 'Get Started Story (Admin)');
    });
  });

  describe('Author User', () => {
    beforeAll(async () => {
      await loginUser('author', 'password');
    });

    afterAll(async () => {
      await switchUserToAdmin();
    });

    it('should prefill post title and post content', async () => {
      await visitAdminPage(
        'post-new.php',
        'post_type=web-story&web-stories-demo=1'
      );

      await expect(page).toMatchElement('input[placeholder="Add title"]');
      await expect(page).toMatch(/Tips to make the most/i);
      await expect(page).toMatch(/to make the most of/i);

      await page.waitForSelector('[data-testid="mediaElement"]');

      await percySnapshot(page, 'Get Started Story (Author)');
    });
  });
});
<|endoftext|>


<commit_before>function FayeAuthentication(endpoint) {
  this._endpoint = endpoint || '/faye/auth';
}

FayeAuthentication.prototype.endpoint = function() {
  return (this._endpoint);
};

FayeAuthentication.prototype.outgoing = function(message, callback) {
  if (message.channel == '/meta/subscribe') {
    $.post(this.endpoint(), message, function(response) {
      message.signature = response.signature;
      callback(message);
    });
  }
  else
    callback(message);
};

FayeAuthentication.prototype.incoming = function(message, callback) {
  callback(message);
};
<commit_msg>Remove un-needed incoming filter for extension<commit_after>function FayeAuthentication(endpoint) {
  this._endpoint = endpoint || '/faye/auth';
}

FayeAuthentication.prototype.endpoint = function() {
  return (this._endpoint);
};

FayeAuthentication.prototype.outgoing = function(message, callback) {
  if (message.channel == '/meta/subscribe') {
    $.post(this.endpoint(), message, function(response) {
      message.signature = response.signature;
      callback(message);
    });
  }
  else
    callback(message);
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var expect = require('chai').expect;
var helpers = require('../helpers');

describe('KycDocuments', function() {
    var john = helpers.data.getUserNatural();
    var document;

    before(function(done){
        api.Users.create(john).then(function(){
            api.Users.createKycDocument(john.Id, {
                Status: 'CREATED',
                Type: 'IDENTITY_PROOF'
            }).then(function(data){
                document = data;
                done();
            });
        });
    });

    describe('Get All', function () {
        var documents;
        before(function(done){
             api.KycDocuments.getAll(function(data, response){
                 documents = data;
                 done();
             }, {
                 parameters: {
                     AfterDate: document.CreationDate - 10,
                     BeforeDate: document.CreationDate + 10
                 }
             });
        });

        it('should contain the created document', function () {
            expect(_.findWhere(documents, {Id: document.Id})).to.exist;
        });
    });

    describe('Get', function () {
        var getDocument;
        before(function(done){
            api.KycDocuments.get(document.Id, function(data, response){
                getDocument = data;
                done();
            });
        });

        it('should get the document', function () {
            expect(getDocument.Id).to.equal(document.Id);
            expect(getDocument.Flags).not.to.be.undefined;
        });
    });

    describe('Create KYC Document Consult', function () {
        var consults;

        before(function(done) {
            api.KycDocuments.createKycDocumentConsult(document.Id, function(data, response) {
                consults = data;
                done();
            });
        });

        it('should be created', function () {
            expect(consults).not.to.be.undefined;
            expect(consults).to.be.an('array');
        });
    });
});
<commit_msg>added test check<commit_after>var _ = require('underscore');
var expect = require('chai').expect;
var helpers = require('../helpers');

describe('KycDocuments', function() {
    var john = helpers.data.getUserNatural();
    var document;

    before(function(done){
        api.Users.create(john).then(function(){
            api.Users.createKycDocument(john.Id, {
                Status: 'CREATED',
                Type: 'IDENTITY_PROOF'
            }).then(function(data){
                document = data;
                done();
            });
        });
    });

    describe('Get All', function () {
        var documents;
        before(function(done){
             api.KycDocuments.getAll(function(data, response){
                 documents = data;
                 done();
             }, {
                 parameters: {
                     AfterDate: document.CreationDate - 10,
                     BeforeDate: document.CreationDate + 10
                 }
             });
        });

        it('should contain the created document', function () {
            expect(_.findWhere(documents, {Id: document.Id})).to.exist;
        });
    });

    describe('Get', function () {
        var getDocument;
        before(function(done){
            api.KycDocuments.get(document.Id, function(data, response){
                getDocument = data;
                done();
            });
        });

        it('should get the document', function () {
            expect(getDocument.Id).to.equal(document.Id);
            expect(getDocument.Flags).not.to.be.undefined;
            expect(getDocument.Flags).to.be.an('array');
        });
    });

    describe('Create KYC Document Consult', function () {
        var consults;

        before(function(done) {
            api.KycDocuments.createKycDocumentConsult(document.Id, function(data, response) {
                consults = data;
                done();
            });
        });

        it('should be created', function () {
            expect(consults).not.to.be.undefined;
            expect(consults).to.be.an('array');
        });
    });
});
<|endoftext|>


<commit_before>/* jshint globalstrict:false, strict:false, unused : false */
/* global fail, assertTrue, assertFalse, assertEqual, TRANSACTION */
// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for transactions
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / 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
// /
// /     http://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.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

var db = require('@arangodb').db;
var internal = require('internal');
var FoxxService = require('@arangodb/foxx/service');
var jsunity = require('jsunity');
var fs = require('fs');

function runSetup () {
  'use strict';
  internal.debugClearFailAt();

  let appPath = fs.join(FoxxService._appPath, '..');

  try {
    db._dropDatabase('UnitTestsRecovery1');
  } catch (err) {}

  db._createDatabase('UnitTestsRecovery1');

  fs.write(fs.join(appPath, 'UnitTestsRecovery1', 'foo.json'), 'test');

  try {
    db._dropDatabase('UnitTestsRecovery2');
  } catch (err) {}

  db._createDatabase('UnitTestsRecovery2');

  fs.write(fs.join(appPath, 'UnitTestsRecovery2', 'bar.json'), 'test');

  db._dropDatabase('UnitTestsRecovery2');

  // we need to wait long enough for the DatabaseManagerThread to
  // physically carry out the deletion
  let path = fs.join(appPath, 'UnitTestsRecovery2');
  let tries = 0;
  while (++tries < 30) {
    if (!fs.isDirectory(path)) {
      break;
    }
    internal.wait(1, false);
  }
  internal.debugTerminate('crashing server');
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  'use strict';
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {},
    tearDown: function () {},

    // //////////////////////////////////////////////////////////////////////////////
    // / @brief test whether the data are correct after restart
    // //////////////////////////////////////////////////////////////////////////////

    testFoxxDirectories: function () {
      var appPath = fs.join(FoxxService._appPath, '..');

      assertTrue(fs.isDirectory(fs.join(appPath, 'UnitTestsRecovery1')));
      assertTrue(fs.isFile(fs.join(appPath, 'UnitTestsRecovery1', 'foo.json')));

      assertFalse(fs.isDirectory(fs.join(appPath, 'UnitTestsRecovery2')));
      assertFalse(fs.isFile(fs.join(appPath, 'UnitTestsRecovery2', 'bar.json')));
    }

  };
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////

function main (argv) {
  'use strict';
  if (argv[1] === 'setup') {
    runSetup();
    return 0;
  } else {
    jsunity.run(recoverySuite);
    return jsunity.writeDone().status ? 0 : 1;
  }
}
<commit_msg>try to debug a spuriously failing test<commit_after>/* jshint globalstrict:false, strict:false, unused : false */
/* global fail, assertTrue, assertFalse, assertEqual, TRANSACTION */
// //////////////////////////////////////////////////////////////////////////////
// / @brief tests for transactions
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / 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
// /
// /     http://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.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////

var db = require('@arangodb').db;
var internal = require('internal');
var FoxxService = require('@arangodb/foxx/service');
var jsunity = require('jsunity');
var fs = require('fs');

function runSetup () {
  'use strict';
  internal.debugClearFailAt();

  let appPath = fs.join(FoxxService._appPath, '..');

  try {
    db._dropDatabase('UnitTestsRecovery1');
  } catch (err) {}

  db._createDatabase('UnitTestsRecovery1');

  fs.write(fs.join(appPath, 'UnitTestsRecovery1', 'foo.json'), 'test');

  try {
    db._dropDatabase('UnitTestsRecovery2');
  } catch (err) {}

  db._createDatabase('UnitTestsRecovery2');

  fs.write(fs.join(appPath, 'UnitTestsRecovery2', 'bar.json'), 'test');

  db._dropDatabase('UnitTestsRecovery2');
  // garbage-collect once
  require("internal").wait(0.5, true);

  // we need to wait long enough for the DatabaseManagerThread to
  // physically carry out the deletion
  let path = fs.join(appPath, 'UnitTestsRecovery2');
  let tries = 0;
  while (++tries < 30) {
    if (!fs.isDirectory(path)) {
      require("console").log("database directory for UnitTestsRecovery2 is gone");
      break;
    }
    internal.wait(1, false);
  }
  internal.debugTerminate('crashing server');
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////

function recoverySuite () {
  'use strict';
  jsunity.jsUnity.attachAssertions();

  return {
    setUp: function () {},
    tearDown: function () {},

    // //////////////////////////////////////////////////////////////////////////////
    // / @brief test whether the data are correct after restart
    // //////////////////////////////////////////////////////////////////////////////

    testFoxxDirectories: function () {
      var appPath = fs.join(FoxxService._appPath, '..');

      assertTrue(fs.isDirectory(fs.join(appPath, 'UnitTestsRecovery1')));
      assertTrue(fs.isFile(fs.join(appPath, 'UnitTestsRecovery1', 'foo.json')));

      assertFalse(fs.isDirectory(fs.join(appPath, 'UnitTestsRecovery2')));
      assertFalse(fs.isFile(fs.join(appPath, 'UnitTestsRecovery2', 'bar.json')));
    }

  };
}

// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////

function main (argv) {
  'use strict';
  if (argv[1] === 'setup') {
    runSetup();
    return 0;
  } else {
    jsunity.run(recoverySuite);
    return jsunity.writeDone().status ? 0 : 1;
  }
}
<|endoftext|>


<commit_before>import { exec } from 'child_process'
import test from 'tape'

import { transactions, config, network, hexStringToECPair, hash160 } from '../../../lib'

function pExec(cmd) {
  return new Promise(
    (resolve, reject) => {
      exec(cmd, (err, stdout, stderr) => {
        if (err) {
          reject(err)
        } else {
          resolve(stdout, stderr)
        }
      })
    })
}

function initializeBlockstackCore() {
  return pExec('docker pull quay.io/blockstack/integrationtests:develop')
    .then(() => {
      console.log('Pulled latest docker image')
      return pExec(`docker stop test-bsk-core ;
        docker rm test-bsk-core ;
        rm -rf /tmp/.blockstack_int_test`)
        .catch(() => true)
    })
    .then(() => pExec('docker run --name test-bsk-core -dt -p 16268:16268 -p 18332:18332 ' +
                      '-e BLOCKSTACK_TEST_CLIENT_RPC_PORT=16268 ' +
                      '-e BLOCKSTACK_TEST_CLIENT_BIND=0.0.0.0 ' +
                      '-e BLOCKSTACK_TEST_BITCOIND_ALLOWIP=172.17.0.0/16 ' +
                      'quay.io/blockstack/integrationtests:develop ' +
                      'blockstack-test-scenario --interactive 2 ' +
                      'blockstack_integration_tests.scenarios.portal_test_env'))
    .then(() => {
      console.log('Started regtest container, waiting until initialized')
      return pExec('docker logs -f test-bsk-core | grep -q \'Test finished\'')
    })
}

function shutdownBlockstackCore() {
  return pExec('docker stop test-bsk-core')
}

export function runIntegrationTests() {
  test('registerName', (t) => {
    t.plan(8)

    config.network = network.defaults.LOCAL_REGTEST
    const myNet = config.network

    const nsPay = '6e50431b955fe73f079469b24f06480aee44e4519282686433195b3c4b5336ef01'
    const nsReveal = 'c244642ce0b4eb68da8e098facfcad889e3063c36a68b7951fb4c085de49df1b'

    const nsRevealAddress = hexStringToECPair(nsPay).getAddress()

    const dest = '19238846ac60fa62f8f8bb8898b03df79bc6112600181f36061835ad8934086001'
    const destAddress = hexStringToECPair(dest).getAddress()

    const btcDest = '897f1b92041b798580f96b8be379053f6276f04eb7590a9042a62059d46d6fc301'
    const btcDestAddress = hexStringToECPair(btcDest).getAddress()

    const payer = 'bb68eda988e768132bc6c7ca73a87fb9b0918e9a38d3618b74099be25f7cab7d01'

    const secondOwner = '54164693e3803223f7fa9a004997bfbf1475f5c44f65593fa45c6783086dafec01'
    const transferDestination = hexStringToECPair(secondOwner).getAddress()

    const renewalDestination = 'myPgwEX2ddQxPPqWBRkXNqL3TwuWbY29DJ'

    const zfTest = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
    const zfTest2 = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
    const renewalZF = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`
    const importZF = '$ORIGIN import.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`

    initializeBlockstackCore()
      .then(() => {
        console.log('Blockstack Core initialized.')
        console.log('Preorder namespace "hello"')
        return transactions.makeNamespacePreorder('hello', nsRevealAddress, nsPay)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_PREORDER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        const ns = transactions.BlockstackNamespace('test')
        ns.setVersion(1)
        ns.setLifetime(52595)
        ns.setCoeff(4)
        ns.setBase(4)
        ns.setBuckets([6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
        ns.setNonalphaDiscount(10)
        ns.setNoVowelDiscount(10)
        console.log('Reveal namespace "hello"')
        return transactions.makeNamespaceReveal(ns, nsRevealAddress, nsPay)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_REVEAL broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        console.log('NAME_IMPORT import.hello')
        const zfHash = hash160(Buffer.from(importZF)).toString()
        return transactions.makeNameImport(
          'import.hello', renewalDestination, zfHash, nsReveal)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAME_IMPORT broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(importZF))
      .then(() => fetch(`${myNet.broadcastAPIUrl}/v1/names/import.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
                `import.hello should be owned by ${renewalDestination}`)
        t.equal(nameInfo.zonefile, importZF, 'zonefile should be properly set for import.hello')
      })
      .then(() => {
        console.log('Launch namespace "hello"')
        return transactions.makeNamespaceReady('hello', nsReveal)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_READY broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        console.log('Namespace initialized.  Preordering aaron.hello')
        return transactions.makePreorder('aaron.hello', destAddress, payer)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('PREORDER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => transactions.makeRegister('aaron.hello', destAddress, payer, zfTest))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('REGISTER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), destAddress,
                `aaron.hello should be owned by ${destAddress}`)
        t.equal(nameInfo.zonefile, zfTest, 'zonefile should be properly set')
      })
      .then(() => transactions.makeUpdate('aaron.hello', dest, payer, zfTest2))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('UPDATE broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest2))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, zfTest2, 'zonefile should be updated')
      })
      .then(() => transactions.makeTransfer('aaron.hello', transferDestination, dest, payer))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('TRANSFER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), transferDestination,
                `aaron.hello should be owned by ${transferDestination}`)
      })
      .then(() => transactions.makeRenewal('aaron.hello', renewalDestination,
                                           secondOwner, payer, renewalZF))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('RENEWAL broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(renewalZF))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
        t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
                `aaron.hello should be owned by ${renewalDestination}`)
      })
      .then(() => transactions.makeRevoke('aaron.hello', secondOwner))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('REVOKE broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.status, 'revoked', 'Name should be revoked')
      })
      .then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('broadcasted SPEND, waiting 10 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.getUTXOs(btcDestAddress))
      .then((utxos) => {
        t.equal(utxos.length, 1, `Destination address ${btcDestAddress} should have 1 UTXO`)
        const satoshis = utxos.reduce((agg, utxo) => agg + utxo.value, 0)
        console.log(`${btcDestAddress} has ${satoshis} satoshis`)
      })
      .then(() => shutdownBlockstackCore())
  })
}
<commit_msg>add back in a test on the id-namespace, fix some type errors in the namespace test<commit_after>import { exec } from 'child_process'
import test from 'tape'

import { transactions, config, network, hexStringToECPair } from '../../../lib'
import { hash160 } from '../../../lib/operations/utils'

function pExec(cmd) {
  return new Promise(
    (resolve, reject) => {
      exec(cmd, (err, stdout, stderr) => {
        if (err) {
          reject(err)
        } else {
          resolve(stdout, stderr)
        }
      })
    })
}

function initializeBlockstackCore() {
  return pExec('docker pull quay.io/blockstack/integrationtests:develop')
    .then(() => {
      console.log('Pulled latest docker image')
      return pExec(`docker stop test-bsk-core ;
        docker rm test-bsk-core ;
        rm -rf /tmp/.blockstack_int_test`)
        .catch(() => true)
    })
    .then(() => pExec('docker run --name test-bsk-core -dt -p 16268:16268 -p 18332:18332 ' +
                      '-e BLOCKSTACK_TEST_CLIENT_RPC_PORT=16268 ' +
                      '-e BLOCKSTACK_TEST_CLIENT_BIND=0.0.0.0 ' +
                      '-e BLOCKSTACK_TEST_BITCOIND_ALLOWIP=172.17.0.0/16 ' +
                      'quay.io/blockstack/integrationtests:develop ' +
                      'blockstack-test-scenario --interactive 2 ' +
                      'blockstack_integration_tests.scenarios.portal_test_env'))
    .then(() => {
      console.log('Started regtest container, waiting until initialized')
      return pExec('docker logs -f test-bsk-core | grep -q \'Test finished\'')
    })
}

function shutdownBlockstackCore() {
  return pExec('docker stop test-bsk-core')
}

export function runIntegrationTests() {
  test('registerIdName', (t) => {
    t.plan(8)

    config.network = network.defaults.LOCAL_REGTEST
    const myNet = config.network

    const dest = '19238846ac60fa62f8f8bb8898b03df79bc6112600181f36061835ad8934086001'
    const destAddress = hexStringToECPair(dest).getAddress()

    const btcDest = '897f1b92041b798580f96b8be379053f6276f04eb7590a9042a62059d46d6fc301'
    const btcDestAddress = hexStringToECPair(btcDest).getAddress()

    const payer = 'bb68eda988e768132bc6c7ca73a87fb9b0918e9a38d3618b74099be25f7cab7d01'

    const secondOwner = '54164693e3803223f7fa9a004997bfbf1475f5c44f65593fa45c6783086dafec01'
    const transferDestination = hexStringToECPair(secondOwner).getAddress()

    const renewalDestination = 'myPgwEX2ddQxPPqWBRkXNqL3TwuWbY29DJ'

    const zfTest = '$ORIGIN aaron.id\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
    const zfTest2 = '$ORIGIN aaron.id\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
    const renewalZF = '$ORIGIN aaron.id\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`

    initializeBlockstackCore()
      .then(() => {
        console.log('Blockstack Core initialized.')
        return transactions.makePreorder('aaron.id', destAddress, payer)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('PREORDER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => transactions.makeRegister('aaron.id', destAddress, payer, zfTest))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('REGISTER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.id`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), destAddress,
                `aaron.id should be owned by ${destAddress}`)
        t.equal(nameInfo.zonefile, zfTest, 'zonefile should be properly set')
      })
      .then(() => transactions.makeUpdate('aaron.id', dest, payer, zfTest2))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('UPDATE broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest2))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.id`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, zfTest2, 'zonefile should be updated')
      })
      .then(() => transactions.makeTransfer('aaron.id', transferDestination, dest, payer))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('TRANSFER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.id`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), transferDestination,
                `aaron.id should be owned by ${transferDestination}`)
      })
      .then(() => transactions.makeRenewal('aaron.id', renewalDestination,
                                           secondOwner, payer, renewalZF))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('RENEWAL broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(renewalZF))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.id`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
        t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
                `aaron.id should be owned by ${renewalDestination}`)
      })
      .then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('broadcasted SPEND, waiting 10 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.getUTXOs(btcDestAddress))
      .then((utxos) => {
        t.equal(utxos.length, 1, `Destination address ${btcDestAddress} should have 1 UTXO`)
        const satoshis = utxos.reduce((agg, utxo) => agg + utxo.value, 0)
        console.log(`${btcDestAddress} has ${satoshis} satoshis`)
      })
      .then(() => shutdownBlockstackCore())
      .then(() => t.pass('Finished test'))
  })

  test('helloNamespace', (t) => {
    t.plan(9)

    config.network = network.defaults.LOCAL_REGTEST
    const myNet = config.network

    const nsPay = '6e50431b955fe73f079469b24f06480aee44e4519282686433195b3c4b5336ef01'
    const nsReveal = 'c244642ce0b4eb68da8e098facfcad889e3063c36a68b7951fb4c085de49df1b'

    const nsRevealAddress = hexStringToECPair(nsPay).getAddress()

    const dest = '19238846ac60fa62f8f8bb8898b03df79bc6112600181f36061835ad8934086001'
    const destAddress = hexStringToECPair(dest).getAddress()

    const btcDest = '897f1b92041b798580f96b8be379053f6276f04eb7590a9042a62059d46d6fc301'
    const btcDestAddress = hexStringToECPair(btcDest).getAddress()

    const payer = 'bb68eda988e768132bc6c7ca73a87fb9b0918e9a38d3618b74099be25f7cab7d01'

    const secondOwner = '54164693e3803223f7fa9a004997bfbf1475f5c44f65593fa45c6783086dafec01'
    const transferDestination = hexStringToECPair(secondOwner).getAddress()

    const renewalDestination = 'myPgwEX2ddQxPPqWBRkXNqL3TwuWbY29DJ'

    const zfTest = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`
    const zfTest2 = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/3/profile.json"`
    const renewalZF = '$ORIGIN aaron.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/4/profile.json"`
    const importZF = '$ORIGIN import.hello\n$TTL 3600\n_http._tcp URI 10 1 ' +
          `"https://gaia.blockstacktest.org/hub/${destAddress}/0/profile.json"`

    initializeBlockstackCore()
      .then(() => {
        console.log('Blockstack Core initialized.')
        console.log('Preorder namespace "hello"')
        return transactions.makeNamespacePreorder('hello', nsRevealAddress, nsPay)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_PREORDER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        const ns = new transactions.BlockstackNamespace('test')
        ns.setVersion(1)
        ns.setLifetime(52595)
        ns.setCoeff(4)
        ns.setBase(4)
        ns.setBuckets([6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
        ns.setNonalphaDiscount(10)
        ns.setNoVowelDiscount(10)
        console.log('Reveal namespace "hello"')
        return transactions.makeNamespaceReveal(ns, nsRevealAddress, nsPay)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_REVEAL broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        console.log('NAME_IMPORT import.hello')
        const zfHash = hash160(Buffer.from(importZF)).toString('hex')
        return transactions.makeNameImport(
          'import.hello', renewalDestination, zfHash, nsReveal)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAME_IMPORT broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(importZF))
      .then(() => fetch(`${myNet.broadcastAPIUrl}/v1/names/import.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
                `import.hello should be owned by ${renewalDestination}`)
        t.equal(nameInfo.zonefile, importZF, 'zonefile should be properly set for import.hello')
      })
      .then(() => {
        console.log('Launch namespace "hello"')
        return transactions.makeNamespaceReady('hello', nsReveal)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('NAMESPACE_READY broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => {
        console.log('Namespace initialized.  Preordering aaron.hello')
        return transactions.makePreorder('aaron.hello', destAddress, payer)
      })
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('PREORDER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => transactions.makeRegister('aaron.hello', destAddress, payer, zfTest))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('REGISTER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), destAddress,
                `aaron.hello should be owned by ${destAddress}`)
        t.equal(nameInfo.zonefile, zfTest, 'zonefile should be properly set')
      })
      .then(() => transactions.makeUpdate('aaron.hello', dest, payer, zfTest2))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('UPDATE broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(zfTest2))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, zfTest2, 'zonefile should be updated')
      })
      .then(() => transactions.makeTransfer('aaron.hello', transferDestination, dest, payer))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('TRANSFER broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(myNet.coerceAddress(nameInfo.address), transferDestination,
                `aaron.hello should be owned by ${transferDestination}`)
      })
      .then(() => transactions.makeRenewal('aaron.hello', renewalDestination,
                                           secondOwner, payer, renewalZF))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('RENEWAL broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.broadcastZoneFile(renewalZF))
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.zonefile, renewalZF, 'zonefile should be updated')
        t.equal(myNet.coerceAddress(nameInfo.address), renewalDestination,
                `aaron.hello should be owned by ${renewalDestination}`)
      })
      .then(() => transactions.makeRevoke('aaron.hello', secondOwner))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('REVOKE broadcasted, waiting 30 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => fetch(`${myNet.blockstackAPIUrl}/v1/names/aaron.hello`))
      .then(resp => resp.json())
      .then(nameInfo => {
        t.equal(nameInfo.status, 'revoked', 'Name should be revoked')
      })
      .then(() => transactions.makeBitcoinSpend(btcDestAddress, payer, 500000))
      .then(rawtx => myNet.broadcastTransaction(rawtx))
      .then(() => {
        console.log('broadcasted SPEND, waiting 10 seconds.')
        return new Promise((resolve) => setTimeout(resolve, 30000))
      })
      .then(() => myNet.getUTXOs(btcDestAddress))
      .then((utxos) => {
        t.equal(utxos.length, 1, `Destination address ${btcDestAddress} should have 1 UTXO`)
        const satoshis = utxos.reduce((agg, utxo) => agg + utxo.value, 0)
        console.log(`${btcDestAddress} has ${satoshis} satoshis`)
      })
      .then(() => shutdownBlockstackCore())
      .then(() => t.pass('Finished test'))
      .catch((err) => {
        console.log(err.stack)
        console.log(err)
      })
  })
}
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(guess,score);

	} while (!finishingScore(score) && turns < 10002);

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var fromTo = function(start,end) {
    var arr = [];
    for (var i=start;i<=end;++i) {
	arr.push(i);
    }
    return arr;
};

var Player = function() {

    this.possibilities = fromTo(0,9999);

    this.guess = function() {
	var n = (Math.random() * this.possibilities.length) | 0;
	var guess = asString(this.possibilities[n]);

	return guess;
    };

    this.eliminateMatches = function(guess, fn) {
	for (var i=0;i<guess.length;++i) {
	    var digit = guess[i];
	    for (var k=this.possibilities.length-1;k>=0;--k) {
		var possibility = this.possibilities[k];
		if (fn(asString(possibility),digit)) {
		    this.possibilities.splice(k,1);
		}
	    }
	}
    };

    this.eliminatePartialMatches = function(guess, n) {
	for (var k=this.possibilities.length-1;k>=0;--k) {
	    var foundCount =  0;
	    for (var i=0;i<guess.length;++i) {
		if (asString(this.possibilities[k]).indexOf(guess[i]) !== -1)
		    foundCount++;
	    }
	    if (foundCount < n)
		this.possibilities.splice(k,1);
	}
    };

    this.update = function(guess,score) {
	if (score.cows === 0 && score.bulls === 0) {
	    // None of the numbers are correct
	    this.eliminateMatches(guess, function(str,digit) {
		return str.indexOf(digit) !== -1;
	    });

	    return;
	}

	if (score.cows + score.bulls > 0) {
	    // Any possibility that doesn't contain at least
	    // score.cows from guess is wrong
	    this.eliminatePartialMatches(guess, score.cows + score.bulls);
	}

	if (score.bulls > 0) {
	    // Any possibility that doesn't contain at least
	    // score.bulls in the same position as guess is wrong
	    for (var i=this.possibilities.length-1; i>=0; --i) {
		var p = asString(this.possibilities[i]);

		var inRightPlace = 0;
		for (var k=0;k<4;++k) {
		    inRightPlace += p[k] === guess[k] ? 1 : 0;
		}

		if (inRightPlace < score.bulls) {
		    this.possibilities.splice(i,1);
		}
	    }
	}

    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

var containsDuplicates = function(str) {
    for (var i=0;i<str.length;++i) {
	var found = false;
	for (var j=0;j<str.length;++j) {
	    if (i === j) continue;

	    if (str[i] === str[j])
		return true;
	}
    }
    return false;
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('slightly intelligently playing', function() {

	it('should solve the game within 9999 turns', function() {
	    for (var i=0;i<100;++i) {
		var game = createGame(asString(Math.random() * 10000 | 0 ));
		var turns = game.play(new Player());

		assert(turns < 10000, 'Too many turns');
	    }
	});

	it('initial pool of answers is 10000', function() {
	    var player = new Player();

	    assert.equal(10000, player.possibilities.length);
	});

	it('zero scores eliminate possibilities', function() {
	    var player = new Player();

	    player.update('1111', { cows: 0, bulls: 0 });

	    assert.equal(6561, player.possibilities.length);
	});

	it('correct guesses eliminate possibilities', function() {
	    var player = new Player();

	    player.update('1234', { cows: 4, bulls: 0 });

	    assert.equal(4*3*2*1, player.possibilities.length);
	});

	it('partial bull matches eliminate many possibilities', function() {
	    var player = new Player();

	    player.update('1234', { cows: 0, bulls: 1 });

	    // all possibilities must have at least one in the right position
	    for (var i=0;i<player.possibilities.length;++i) {
		var remaining = asString(player.possibilities[i]);

		assert(remaining[0] === '1' ||
		       remaining[1] === '2' ||
		       remaining[2] === '3' ||
		       remaining[3] === '4');
	    }
	});

	it('partial matches eliminate possibilites', function() {
	    var player = new Player();

	    player.update('1234', { cows: 2, bulls: 0 });

	    assert.equal(4284, player.possibilities.length);
	    for (var i=0;i<player.possibilities.length;++i) {
		var v = asString(player.possibilities[i]);

		var count = 0;
		for (var k=1;k<=4;++k)
		    count += v.indexOf(k + '') !== -1 ? 1 : 0;
		assert(count >= 2);
	    }
	});

	it('partial matches eliminate possibilities (2)', function() {
	    var player = new Player();

	    player.update('1111', { cows: 1, bulls: 0 });
	    assert.equal(3439, player.possibilities.length);
	    for (var i=0;i<player.possibilities.length;++i) {
		assert(-1 != asString(player.possibilities[i]).indexOf('1'));
	    }
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<commit_msg>start debugging and instrumenting to find problem<commit_after>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(guess,score);

	} while (!finishingScore(score) && turns < 10002);

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var fromTo = function(start,end) {
    var arr = [];
    for (var i=start;i<=end;++i) {
	arr.push(i);
    }
    return arr;
};

var Player = function() {

    this.possibilities = fromTo(0,9999);

    this.guess = function() {
	var n = (Math.random() * this.possibilities.length) | 0;
	var guess = asString(this.possibilities[n]);

	return guess;
    };

    this.eliminateMatches = function(guess, fn) {
	for (var i=0;i<guess.length;++i) {
	    var digit = guess[i];
	    for (var k=this.possibilities.length-1;k>=0;--k) {
		var possibility = this.possibilities[k];
		if (fn(asString(possibility),digit)) {
		    this.possibilities.splice(k,1);
		}
	    }
	}
    };

    this.eliminatePartialMatches = function(guess, n) {
	for (var k=this.possibilities.length-1;k>=0;--k) {
	    var foundCount =  0;
	    for (var i=0;i<guess.length;++i) {
		if (asString(this.possibilities[k]).indexOf(guess[i]) !== -1)
		    foundCount++;
	    }
	    if (foundCount < n)
		this.possibilities.splice(k,1);
	}
    };

    this.update = function(guess,score) {
	if (score.cows === 0 && score.bulls === 0) {
	    // None of the numbers are correct
	    this.eliminateMatches(guess, function(str,digit) {
		return str.indexOf(digit) !== -1;
	    });

	    return;
	}

	if (score.cows + score.bulls > 0) {
	    // Any possibility that doesn't contain at least
	    // score.cows from guess is wrong
	    this.eliminatePartialMatches(guess, score.cows + score.bulls);
	}

	if (score.bulls > 0) {
	    // Any possibility that doesn't contain at least
	    // score.bulls in the same position as guess is wrong
	    for (var i=this.possibilities.length-1; i>=0; --i) {
		var p = asString(this.possibilities[i]);

		var inRightPlace = 0;
		for (var k=0;k<4;++k) {
		    inRightPlace += p[k] === guess[k] ? 1 : 0;
		}

		if (inRightPlace < score.bulls) {
		    this.possibilities.splice(i,1);
		}
	    }
	}

    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

var containsDuplicates = function(str) {
    for (var i=0;i<str.length;++i) {
	var found = false;
	for (var j=0;j<str.length;++j) {
	    if (i === j) continue;

	    if (str[i] === str[j])
		return true;
	}
    }
    return false;
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('slightly intelligently playing', function() {

	it.only('should solve the game within 9999 turns', function() {
	    for (var i=0;i<100;++i) {
		var goal = asString(Math.random() * 10000 | 0);
		var game = createGame(goal);
		var turns = game.play(new Player());

		assert(turns < 10000, 'Too many turns to solve: ' + goal);
	    }
	});

	it('initial pool of answers is 10000', function() {
	    var player = new Player();

	    assert.equal(10000, player.possibilities.length);
	});

	it('zero scores eliminate possibilities', function() {
	    var player = new Player();

	    player.update('1111', { cows: 0, bulls: 0 });

	    assert.equal(6561, player.possibilities.length);
	});

	it('correct guesses eliminate possibilities', function() {
	    var player = new Player();

	    player.update('1234', { cows: 4, bulls: 0 });

	    assert.equal(4*3*2*1, player.possibilities.length);
	});

	it('partial bull matches eliminate many possibilities', function() {
	    var player = new Player();

	    player.update('1234', { cows: 0, bulls: 1 });

	    // all possibilities must have at least one in the right position
	    for (var i=0;i<player.possibilities.length;++i) {
		var remaining = asString(player.possibilities[i]);

		assert(remaining[0] === '1' ||
		       remaining[1] === '2' ||
		       remaining[2] === '3' ||
		       remaining[3] === '4');
	    }
	});

	it('partial matches eliminate possibilites', function() {
	    var player = new Player();

	    player.update('1234', { cows: 2, bulls: 0 });

	    assert.equal(4284, player.possibilities.length);
	    for (var i=0;i<player.possibilities.length;++i) {
		var v = asString(player.possibilities[i]);

		var count = 0;
		for (var k=1;k<=4;++k)
		    count += v.indexOf(k + '') !== -1 ? 1 : 0;
		assert(count >= 2);
	    }
	});

	it('partial matches eliminate possibilities (2)', function() {
	    var player = new Player();

	    player.update('1111', { cows: 1, bulls: 0 });
	    assert.equal(3439, player.possibilities.length);
	    for (var i=0;i<player.possibilities.length;++i) {
		assert(-1 != asString(player.possibilities[i]).indexOf('1'));
	    }
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(score);
	} while (!finishingScore(score));

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var Player = function() {

    this.guess = function() {
	return asString(1234);
    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('intelligently playing', function() {

	var containsDuplicates = function(str) {
	    for (var i=0;i<str.length;++i) {
		var found = false;
		for (var j=0;j<str.length;++j) {
		    if (i === j) continue;

		    if (str[i] === str[j])
			return true;
		}
	    }
	    return false;
	};

	it('should have four unique numbers in initial guess', function() {
	    var player = new Player();

	    var initialGuess = player.guess();
	    assert(!containsDuplicates(initialGuess), 'no duplicates');
	});

	it('initial pool of answers is 9999', function() {
	    var player = new Player();

	    assert.equal(9999, player.possibilities.length);
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<commit_msg>make the test pass minimally and adjust expectations<commit_after>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(score);
	} while (!finishingScore(score));

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var fromTo = function(start,end) {
    var arr = [];
    for (var i=start;i<=end;++i) {
	arr.push(i);
    }
    return arr;
};

var Player = function() {

    this.possibilities = fromTo(0,9999);

    this.guess = function() {
	return asString(1234);
    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('intelligently playing', function() {

	var containsDuplicates = function(str) {
	    for (var i=0;i<str.length;++i) {
		var found = false;
		for (var j=0;j<str.length;++j) {
		    if (i === j) continue;

		    if (str[i] === str[j])
			return true;
		}
	    }
	    return false;
	};

	it('should have four unique numbers in initial guess', function() {
	    var player = new Player();

	    var initialGuess = player.guess();
	    assert(!containsDuplicates(initialGuess), 'no duplicates');
	});

	it('initial pool of answers is 10000', function() {
	    var player = new Player();

	    assert.equal(10000, player.possibilities.length);
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<|endoftext|>


<commit_before>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const periodic = require('../../../index');
const periodicClass = require('../../../lib/periodicClass');
const lowkieSchema = require('../../../lib/defaults/schema/lowkie.schema');
const mongooseSchema = require('../../../lib/defaults/schema/mongoose.schema');
const sequelizeSchema = require('../../../lib/defaults/schema/sequelize.schema');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));

describe('Periodic lib defaults schema', function() {
  this.timeout(10000);
  describe('mongoose', () => {
    it('should return model scheme', () => {
      expect(mongooseSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(mongooseSchema('item').entitytype.default).to.eql('item');
    });
  });
  describe('sequelize', () => {
    it('should return model scheme', () => {
      expect(sequelizeSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(sequelizeSchema('item').entitytype.default).to.eql('item');
    });
  });
  describe('lowkie', () => {
    it('should return model scheme', () => {
      expect(lowkieSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(lowkieSchema('item').entitytype.default).to.eql('item');
    });
  });
});<commit_msg>adding more sql tests<commit_after>'use strict';
/*jshint expr: true*/
const path = require('path');
const events = require('events');
const chai = require('chai');
const sinon = require('sinon');
const fs = require('fs-extra');
const expect = require('chai').expect;
const periodic = require('../../../index');
const periodicClass = require('../../../lib/periodicClass');
const lowkieSchema = require('../../../lib/defaults/schema/lowkie.schema');
const mongooseSchema = require('../../../lib/defaults/schema/mongoose.schema');
const sequelizeSchema = require('../../../lib/defaults/schema/sequelize.schema');
chai.use(require('sinon-chai'));
chai.use(require('chai-as-promised'));

describe('Periodic lib defaults schema', function() {
  this.timeout(10000);
  describe('mongoose', () => {
    it('should return model scheme', () => {
      expect(mongooseSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(mongooseSchema('item').entitytype.default).to.eql('item');
    });
  });
  describe('sequelize', () => {
    const itemScheme = sequelizeSchema('item');
    const sampleJson = { data: 'test' };
    const stringifiedSampleJson = JSON.stringify(sampleJson);
    const setDataValueSpy = sinon.spy();
    const mockThis = {
      getDataValue: (val) => stringifiedSampleJson,
      setDataValue: setDataValueSpy,
    };
    it('should return model scheme', () => {
      expect(sequelizeSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(sequelizeSchema('item').entitytype.default).to.eql('item');
    });
    it('should retrieve _attributes, contenttypeattributes, extensionattributes as json', () => {
      expect(itemScheme._attributes.get.call(mockThis)).to.eql(sampleJson)
      expect(itemScheme.contenttypeattributes.get.call(mockThis)).to.eql(sampleJson)
      expect(itemScheme.extensionattributes.get.call(mockThis)).to.eql(sampleJson)
    });
    it('should store _attributes, contenttypeattributes, extensionattributes as json', () => {
      itemScheme._attributes.set.call(mockThis, sampleJson);
      expect(setDataValueSpy.called).to.be.true;
      itemScheme.contenttypeattributes.set.call(mockThis,sampleJson)
      expect(setDataValueSpy.called).to.be.true;
      itemScheme.extensionattributes.set.call(mockThis,sampleJson)
      expect(setDataValueSpy.called).to.be.true;
    });
  });
  describe('lowkie', () => {
    it('should return model scheme', () => {
      expect(lowkieSchema('example')).to.be.an('object');
    });
    it('should set entity type', () => {
      expect(lowkieSchema('item').entitytype.default).to.eql('item');
    });
  });
});<|endoftext|>


<commit_before>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

// test('Create slide with correct data', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   compareSlideData(slide.data, dataForSlide);
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Create slide with empty data', function() {
//   var slide = new TestimonialSlide();
//   ok(slide.data !== undefined, 'Slide has empty data');
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Slide css class', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   ok(slide.$slide.attr('class') === 'testimonial_slide', 'New slide has correct css class');
// });

// test('Create slide data of empty data', function() {
//   var slideData = TestimonialSlide.prototype.createData();
//   ok(slideData !== undefined, 'Slide data not empty');
//   compareSlideData(slideData, emptydata);
// });

// test('Create slide data of correct data', function() {
//   var slideData = TestimonialSlide.prototype.createData(dataForSlide);
//   compareSlideData(slideData, dataForSlide);
// });

test('Create options', function() {
  TestimonialSlide.prototype.createOptions();
  ok(TestimonialSlide.prototype.options.duration === 750, '');
  ok(TestimonialSlide.prototype.options.distance === 250, '');
});
<commit_msg>Add test<commit_after>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

// test('Create slide with correct data', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   compareSlideData(slide.data, dataForSlide);
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Create slide with empty data', function() {
//   var slide = new TestimonialSlide();
//   ok(slide.data !== undefined, 'Slide has empty data');
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Slide css class', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   ok(slide.$slide.attr('class') === 'testimonial_slide', 'New slide has correct css class');
// });

// test('Create slide data of empty data', function() {
//   var slideData = TestimonialSlide.prototype.createData();
//   ok(slideData !== undefined, 'Slide data not empty');
//   compareSlideData(slideData, emptydata);
// });

// test('Create slide data of correct data', function() {
//   var slideData = TestimonialSlide.prototype.createData(dataForSlide);
//   compareSlideData(slideData, dataForSlide);
// });

// test('Create options', function() {
//   TestimonialSlide.prototype.createOptions();
//   ok(TestimonialSlide.prototype.options.duration === 750, '');
//   ok(TestimonialSlide.prototype.options.distance === 250, '');
// });

test('Get DOM node', function() {
  var testId = 'testId';
  var domNode = $('<div />', { id: testId });
  TestimonialSlide.prototype.$slide = domNode;
  var $expectedDomNode = TestimonialSlide.prototype.getNode();
  ok($expectedDomNode.attr('id') === testId , '');
});
<|endoftext|>