← run

bcb-0027

1.000
5/5 tests· lib-knowledge
Challenge · difficulty 2/5
# BigCodeBench/27

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

Allowed libraries: `base64`, `json`, `datetime`.

```python
import json
import base64
from datetime import datetime

def task_func(data: dict, DATE_FORMAT = "%Y-%m-%d %H:%M:%S") -> str:
    """
    Takes a Python dictionary, adds a current timestamp to it, serializes the modified dictionary
    to a JSON-formatted string, and then encodes this string using base64 encoding with ASCII character encoding.
    
    Parameters:
    data (dict): The Python dictionary to encode. The dictionary should not contain a key named 'timestamp',
                 as this key is used to insert the current timestamp by the function. The input dictionary
                 is modified in-place by adding the 'timestamp' key.
    
    Returns:
    str: A base64 encoded string that represents the input dictionary with an added timestamp,
         encoded in ASCII. The timestamp is added with the key 'timestamp'.
    DATE_FORMAT: The timestamp format. Default to 'YYYY-MM-DD HH:MM:SS'.
         
    Requirements:
    - json
    - base64
    - datetime.datetime
    
    Example:
    >>> data = {'name': 'John', 'age': 30, 'city': 'New York'}
    >>> encoded_data = task_func(data)
    >>> isinstance(encoded_data, str)
    True
    """
```

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

import unittest
import json
import base64
from datetime import datetime
class TestCases(unittest.TestCase):
    
    def test_task_func_basic(self):
        """Test the task_func function with a basic dictionary."""
        data = {'name': 'John', 'age': 30, 'city': 'New York'}
        encoded_data = task_func(data)
        decoded_data = json.loads(base64.b64decode(encoded_data).decode('ascii'))
        self.assertEqual(data['name'], decoded_data['name'])
        self.assertEqual(data['age'], decoded_data['age'])
        self.assertEqual(data['city'], decoded_data['city'])
        self.assertIn('timestamp', decoded_data)
        self.assertIsInstance(datetime.strptime(decoded_data['timestamp'], "%Y-%m-%d %H:%M:%S"), datetime)
        
    def test_task_func_empty(self):
        """Test the task_func function with an empty dictionary."""
        data = {}
        encoded_data = task_func(data)
        decoded_data = json.loads(base64.b64decode(encoded_data).decode('ascii'))
        self.assertEqual(len(decoded_data), 1)
        self.assertIn('timestamp', decoded_data)
        self.assertIsInstance(datetime.strptime(decoded_data['timestamp'], "%Y-%m-%d %H:%M:%S"), datetime)
        
    def test_task_func_nested(self):
        """Test the task_func function with a nested dictionary."""
        data = {'user': {'name': 'John', 'age': 30}, 'location': {'city': 'New York', 'country': 'USA'}}
        encoded_data = task_func(data)
        decoded_data = json.loads(base64.b64decode(encoded_data).decode('ascii'))
        self.assertEqual(data['user'], decoded_data['user'])
        self.assertEqual(data['location'], decoded_data['location'])
        self.assertIn('timestamp', decoded_data)
        self.assertIsInstance(datetime.strptime(decoded_data['timestamp'], "%Y-%m-%d %H:%M:%S"), datetime)
        
    def test_task_func_numeric(self):
        """Test the task_func function with a dictionary containing numeric keys."""
        data = {1: 10, 2: 20, 3: 30}
        encoded_data = task_func(data)
        decoded_data = json.loads(base64.b64decode(encoded_data).decode('ascii'))
        data_str_keys = {str(k): v for k, v in data.items()}
        for k, v in data_str_keys.items():
            self.assertEqual(v, decoded_data[k])
        self.assertIn('timestamp', decoded_data)
        self.assertIsInstance(datetime.strptime(decoded_data['timestamp'], "%Y-%m-%d %H:%M:%S"), datetime)
        
    def test_task_func_mixed(self):
        """Test the task_func function with a dictionary containing mixed types of keys and values."""
        data = {'name': 'John', 1: 30, 'nested': {'key': 'value'}, 'list': [1, 2, 3]}
        encoded_data = task_func(data)
        decoded_data = json.loads(base64.b64decode(encoded_data).decode('ascii'))
        data_str_keys = {str(k): v for k, v in data.items()}
        for k, v in data_str_keys.items():
            self.assertEqual(v, decoded_data[k])
        self.assertIn('timestamp', decoded_data)
        self.assertIsInstance(datetime.strptime(decoded_data['timestamp'], "%Y-%m-%d %H:%M:%S"), datetime)
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
```python
import json
import base64
from datetime import datetime

def task_func(data: dict, DATE_FORMAT = "%Y-%m-%d %H:%M:%S") -> str:
    """
    Takes a Python dictionary, adds a current timestamp to it, serializes the modified dictionary
    to a JSON-formatted string, and then encodes this string using base64 encoding with ASCII character encoding.
    
    Parameters:
    data (dict): The Python dictionary to encode. The dictionary should not contain a key named 'timestamp',
                 as this key is used to insert the current timestamp by the function. The input dictionary
                 is modified in-place by adding the 'timestamp' key.
    
    Returns:
    str: A base64 encoded string that represents the input dictionary with an added timestamp,
         encoded in ASCII. The timestamp is added with the key 'timestamp'.
    DATE_FORMAT: The timestamp format. Default to 'YYYY-MM-DD HH:MM:SS'.
         
    Requirements:
    - json
    - base64
    - datetime.datetime
    
    Example:
    >>> data = {'name': 'John', 'age': 30, 'city': 'New York'}
    >>> encoded_data = task_func(data)
    >>> isinstance(encoded_data, str)
    True
    """
    # Add the current timestamp to the dictionary
    data['timestamp'] = datetime.now().strftime(DATE_FORMAT)
    
    # Serialize the modified dictionary to a JSON-formatted string
    json_str = json.dumps(data)
    
    # Encode the JSON string using base64 encoding with ASCII character encoding
    encoded_str = base64.b64encode(json_str.encode('ascii')).decode('ascii')
    
    return encoded_str
```

Test output (stdout)

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