← run

bcb-0007

1.000
7/7 tests· lib-knowledge
Challenge · difficulty 3/5
# BigCodeBench/7

Implement a file **`solution.py`** that completes the function below. Keep the given name and signature; define `task_func` at module level.

Allowed libraries: `operator`, `csv`, `collections`.

```python
import csv
import collections
import operator

def task_func(csv_file_path):
    """
    Find the best-selling product from a given CSV file with sales data.

    This function parses a CSV file assumed to have a header followed by rows containing
    two columns: 'product' and 'quantity'. It computes the total sales per product and
    determines the product with the highest cumulative sales. The CSV file must include
    at least these two columns, where 'product' is the name of the product as a string
    and 'quantity' is the number of units sold as an integer.

    Args:
        csv_file_path (str): The file path to the CSV file containing sales data.

    Returns:
        str: The name of the top-selling product based on the total quantity sold.

    Requirements:
    - csv
    - collections
    - operator

    Example:
    >>> task_func("path/to/sales.csv")
    'Product ABC'
    """
```

<!-- imported from BigCodeBench (BigCodeBench/7) -->
tests/test_bcb_0007.py
# Auto-generated from BigCodeBench BigCodeBench/7. Do not edit by hand.
import pathlib as _pathlib
exec(_pathlib.Path(__file__).with_name("solution.py").read_text(), globals())

import os
import unittest
import csv
class TestCases(unittest.TestCase):
    def setUp(self):
        # Create a directory for test files if it does not exist
        self.test_dir = os.path.join(os.getcwd(), 'test_data')
        os.makedirs(self.test_dir, exist_ok=True)
    def tearDown(self):
        # Remove all files created in the test directory
        for filename in os.listdir(self.test_dir):
            file_path = os.path.join(self.test_dir, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)
    def test_case_1(self):
        # Correct data, expected top-seller is determined correctly
        self.create_csv('sales1.csv', [['product', 'quantity'], ['Product B', '200'], ['Product A', '100']])
        result = task_func(os.path.join(self.test_dir, "sales1.csv"))
        self.assertEqual(result, "Product B")
    def test_case_2(self):
        # Correct data, expected top-seller is determined correctly
        self.create_csv('sales2.csv', [['product', 'quantity'], ['Product Z', '120'], ['Product Y', '80']])
        result = task_func(os.path.join(self.test_dir, "sales2.csv"))
        self.assertEqual(result, "Product Z")
    def test_case_3(self):
        # Correct data, expected top-seller is determined correctly
        self.create_csv('sales3.csv', [['product', 'quantity'], ['Product M', '500'], ['Product N', '400']])
        result = task_func(os.path.join(self.test_dir, "sales3.csv"))
        self.assertEqual(result, "Product M")
    def test_case_4(self):
        # Empty file with header, expect a ValueError or a graceful handle
        self.create_csv('sales4.csv', [['product', 'quantity']])
        with self.assertRaises(ValueError):
            task_func(os.path.join(self.test_dir, "sales4.csv"))
    def test_case_5(self):
        # Single product data, correct determination
        self.create_csv('sales5.csv', [['product', 'quantity'], ['Single Product', '999']])
        result = task_func(os.path.join(self.test_dir, "sales5.csv"))
        self.assertEqual(result, "Single Product")
    def test_case_6(self):
        # File does not exist, expect FileNotFoundError
        with self.assertRaises(FileNotFoundError):
            task_func(os.path.join(self.test_dir, "nonexistent.csv"))
    def test_case_7(self):
        # Incorrect data types, expect ValueError or graceful handling of conversion failure
        self.create_csv('sales6.csv', [['product', 'quantity'], ['Product A', 'one hundred']])
        with self.assertRaises(ValueError):
            task_func(os.path.join(self.test_dir, "sales6.csv"))
    def create_csv(self, filename, rows):
        # Helper function to create CSV files with given rows
        path = os.path.join(self.test_dir, filename)
        with open(path, 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerows(rows)
Proposed solution
```python
import csv
import collections
import operator

def task_func(csv_file_path):
    sales = collections.Counter()
    with open(csv_file_path, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            sales[row['product']] += int(row['quantity'])
    return max(sales, key=sales.get)
```

Test output (stdout)

.......                                                                  [100%]
7 passed in 0.02s