<?php

/**
 * @file
 * Ubercart stock related tests
 */

class UbercartStockTestCase extends UbercartTestHelper {

  public static function getInfo() {
    return array(
      'name' => 'Stock',
      'description' => 'Ensure that stock control functions properly.',
      'group' => 'Ubercart',
    );
  }

  public function setUp() {
    parent::setUp(array('uc_stock'), array('administer product stock'));
    $this->drupalLogin($this->adminUser);
  }

  public function testProductStock() {
    $this->drupalGet('node/' . $this->product->nid . '/edit/stock');
    $this->assertText($this->product->title);
    $this->assertText($this->product->model, 'Product SKU found.');

    $this->assertNoFieldChecked('edit-stock-0-active', 'Stock tracking is not active.');
    $this->assertFieldByName('stock[0][stock]', '0', 'Default stock level found.');
    $this->assertFieldByName('stock[0][threshold]', '0', 'Default stock threshold found.');

    $stock = rand(1, 1000);
    $edit = array(
      'stock[0][active]' => 1,
      'stock[0][stock]' => $stock,
      'stock[0][threshold]' => rand(1, 100),
    );
    $this->drupalPost(NULL, $edit, t('Save changes'));
    $this->assertText('Stock settings saved.');
    $this->assertTrue(uc_stock_is_active($this->product->model));
    $this->assertEqual($stock, uc_stock_level($this->product->model));

    $stock = rand(1, 1000);
    uc_stock_set($this->product->model, $stock);
    $this->drupalGet('node/' . $this->product->nid . '/edit/stock');
    $this->assertFieldByName('stock[0][stock]', (string)$stock, 'Set stock level found.');
  }

  public function testStockDecrement() {
    $stock = rand(100, 1000);
    $edit = array(
      'stock[0][active]' => 1,
      'stock[0][stock]' => $stock,
    );
    $this->drupalPost('node/' . $this->product->nid . '/edit/stock', $edit, t('Save changes'));
    $this->assertText('Stock settings saved.');

    // Enable product quantity field.
    variable_set('uc_product_add_to_cart_qty', TRUE);

    $qty = rand(1, 100);
    $edit = array('qty' => $qty);
    $this->drupalPost('node/' . $this->product->nid, $edit, t('Add to cart'));

    $this->checkout();

    $this->assertEqual($stock - $qty, uc_stock_level($this->product->model));
  }
}
