Bird
Raised Fist0
Apache Sparkdata~20 mins

Integration testing pipelines in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Integration Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Spark DataFrame after pipeline transformation
Given the following Spark pipeline code, what is the output DataFrame content after applying the transformations?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer, VectorAssembler

spark = SparkSession.builder.master('local').appName('Test').getOrCreate()
data = [(0, 'cat'), (1, 'dog'), (2, 'cat'), (3, 'bird')]
schema = ['id', 'animal']
df = spark.createDataFrame(data, schema)

indexer = StringIndexer(inputCol='animal', outputCol='animalIndex')
assembler = VectorAssembler(inputCols=['animalIndex'], outputCol='features')
pipeline = Pipeline(stages=[indexer, assembler])
model = pipeline.fit(df)
result = model.transform(df).select('id', 'animal', 'animalIndex', 'features')
result.show()
A[Row(id=0, animal='cat', animalIndex=0.0, features=DenseVector([0.0])), Row(id=1, animal='dog', animalIndex=1.0, features=DenseVector([1.0])), Row(id=2, animal='cat', animalIndex=0.0, features=DenseVector([0.0])), Row(id=3, animal='bird', animalIndex=2.0, features=DenseVector([2.0]))]
B[Row(id=0, animal='cat', animalIndex=1.0, features=DenseVector([0.0])), Row(id=1, animal='dog', animalIndex=2.0, features=DenseVector([1.0])), Row(id=2, animal='cat', animalIndex=1.0, features=DenseVector([0.0])), Row(id=3, animal='bird', animalIndex=0.0, features=DenseVector([2.0]))]
C[Row(id=0, animal='cat', animalIndex=2.0, features=DenseVector([2.0])), Row(id=1, animal='dog', animalIndex=0.0, features=DenseVector([0.0])), Row(id=2, animal='cat', animalIndex=2.0, features=DenseVector([2.0])), Row(id=3, animal='bird', animalIndex=1.0, features=DenseVector([1.0]))]
D[Row(id=0, animal='cat', animalIndex=1.0, features=DenseVector([1.0])), Row(id=1, animal='dog', animalIndex=2.0, features=DenseVector([2.0])), Row(id=2, animal='cat', animalIndex=1.0, features=DenseVector([1.0])), Row(id=3, animal='bird', animalIndex=0.0, features=DenseVector([0.0]))]
Attempts:
2 left
💡 Hint
Remember StringIndexer assigns indices based on label frequency descending order.
❓ data_output
intermediate
1:30remaining
Number of rows after filtering in Spark pipeline
Consider a Spark DataFrame with 1000 rows. A pipeline stage filters rows where the column 'age' is greater than 30. If 400 rows have age > 30, how many rows remain after the pipeline transformation?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.sql.functions import col

spark = SparkSession.builder.master('local').appName('Test').getOrCreate()
data = [(i, 20 + (i % 50)) for i in range(1000)]
schema = ['id', 'age']
df = spark.createDataFrame(data, schema)

class AgeFilter:
    def __init__(self, age_limit):
        self.age_limit = age_limit
    def transform(self, df):
        return df.filter(col('age') > self.age_limit)
    def fit(self, df):
        return self

filter_stage = AgeFilter(30)
pipeline = Pipeline(stages=[filter_stage])
model = pipeline.fit(df)
result = model.transform(df)
count = result.count()
A1000
B400
C600
D0
Attempts:
2 left
💡 Hint
Count how many rows satisfy the condition age > 30.
🔧 Debug
advanced
2:00remaining
Identify the error in Spark pipeline code
What error does the following Spark pipeline code raise when executed?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import StringIndexer

spark = SparkSession.builder.master('local').appName('Test').getOrCreate()
data = [(0, 'apple'), (1, 'banana')]
schema = ['id', 'fruit']
df = spark.createDataFrame(data, schema)

indexer = StringIndexer(inputCol='fruit', outputCol='fruitIndex')
pipeline = Pipeline(stages=[indexer])
model = pipeline.fit(df)
result = model.transform(df).select('id', 'fruitIndex')
result.show()
ANo error, outputs DataFrame with 'id' and 'fruitIndex' columns
BTypeError: 'StringIndexer' object is not callable
CAnalysisException: cannot resolve 'fruitIndex' given input columns: [id, fruit]
DAttributeError: 'Pipeline' object has no attribute 'fit'
Attempts:
2 left
💡 Hint
Check if the pipeline stages are correctly defined and used.
🚀 Application
advanced
1:30remaining
Best approach to test Spark pipeline integration
Which approach is best to test the integration of multiple Spark pipeline stages in a data science project?
AOnly test the pipeline on production data to ensure real-world correctness
BTest each pipeline stage separately with unit tests and skip full pipeline testing
CRun the full pipeline on a small sample dataset and verify the final output matches expected results
DManually inspect intermediate DataFrame outputs without automated tests
Attempts:
2 left
💡 Hint
Integration testing means testing combined parts together.
🧠 Conceptual
expert
2:00remaining
Effect of caching in Spark pipeline integration tests
In Spark pipeline integration tests, what is the main benefit of caching intermediate DataFrames during the pipeline execution?
AIt speeds up repeated access to intermediate results, reducing test runtime
BIt automatically fixes data quality issues in intermediate DataFrames
CIt prevents the pipeline from running any transformations
DIt increases memory usage without any performance benefit
Attempts:
2 left
💡 Hint
Think about how caching affects performance in Spark.

Practice

(1/5)
1. What is the main goal of integration testing pipelines in Apache Spark?
easy
A. To check if all parts of the data pipeline work together correctly
B. To test only individual functions separately
C. To deploy the pipeline to production without testing
D. To write documentation for the pipeline

Solution

  1. Step 1: Understand integration testing purpose

    Integration testing checks if different parts of a system work together as expected.
  2. Step 2: Apply to Spark pipelines

    In Spark, integration testing ensures all pipeline stages (data reading, transformation, writing) function together correctly.
  3. Final Answer:

    To check if all parts of the data pipeline work together correctly -> Option A
  4. Quick Check:

    Integration testing = check all parts together [OK]
Hint: Integration tests check combined parts, not single functions [OK]
Common Mistakes:
  • Confusing integration testing with unit testing
  • Skipping tests before deployment
  • Thinking integration tests only check code style
2. Which of the following is the correct way to create a small sample DataFrame for integration testing in Spark using Python?
easy
A. spark.makeDataFrame([(1, 'a'), (2, 'b')], ['id', 'value'])
B. spark.createDataFrame([(1, 'a'), (2, 'b')], ['id', 'value'])
C. spark.newDataFrame([(1, 'a'), (2, 'b')], ['id', 'value'])
D. spark.DataFrame.create([(1, 'a'), (2, 'b')], ['id', 'value'])

Solution

  1. Step 1: Recall Spark DataFrame creation syntax

    The correct method to create a DataFrame from a list in PySpark is spark.createDataFrame(data, schema).
  2. Step 2: Match options with correct syntax

    Only spark.createDataFrame([(1, 'a'), (2, 'b')], ['id', 'value']) uses spark.createDataFrame correctly with data and column names.
  3. Final Answer:

    spark.createDataFrame([(1, 'a'), (2, 'b')], ['id', 'value']) -> Option B
  4. Quick Check:

    Use spark.createDataFrame() to make test data [OK]
Hint: Remember: spark.createDataFrame() is the correct method [OK]
Common Mistakes:
  • Using non-existent methods like newDataFrame or makeDataFrame
  • Calling createDataFrame on DataFrame class instead of spark session
  • Passing schema incorrectly
3. Given the following Spark code for integration testing, what will be the output of result_df.collect()?
input_df = spark.createDataFrame([(1, 10), (2, 20)], ['id', 'value'])
result_df = input_df.withColumn('value_plus_one', input_df['value'] + 1)
medium
A. [(1, 10), (2, 20)]
B. [(1, 11), (2, 21)]
C. [(1, 10, 11), (2, 20, 21)]
D. Error: withColumn requires a string as first argument

Solution

  1. Step 1: Understand withColumn usage

    withColumn adds a new column with the given name and values. Here, 'value_plus_one' is added as 'value' + 1.
  2. Step 2: Calculate new column values

    For id=1, value=10, value_plus_one=11; for id=2, value=20, value_plus_one=21.
  3. Final Answer:

    [(1, 10, 11), (2, 20, 21)] -> Option C
  4. Quick Check:

    withColumn adds new column with value+1 [OK]
Hint: withColumn adds new column; check column names carefully [OK]
Common Mistakes:
  • Thinking withColumn replaces existing columns
  • Ignoring the new column added
  • Confusing collect() output format
4. You wrote this integration test code but it fails with an error. What is the mistake?
test_df = spark.createDataFrame([(1, 'x'), (2, 'y')], ['id', 'value'])
result_df = test_df.filter(test_df['value'] > 1)
result_df.show()
medium
A. DataFrame creation syntax is wrong
B. Column name 'value' is incorrect
C. Missing import for filter function
D. Cannot compare string column with '>' operator in Spark

Solution

  1. Step 1: Analyze filter condition

    The filter uses '>' to compare string column 'value' with 1. Spark does not support '>' between string and integer.
  2. Step 2: Understand Spark comparisons

    For mixed types, cast the column e.g. F.col('value').cast('int') or ensure matching types, not direct '>' operator.
  3. Final Answer:

    Cannot compare string column with '>' operator in Spark -> Option D
  4. Quick Check:

    Compatible types required for '>' in Spark filters [OK]
Hint: Cast types before using comparison operators in Spark [OK]
Common Mistakes:
  • Assuming '>' works between strings and numbers in Spark
  • Misnaming columns
  • Forgetting to import Spark functions
5. You want to write an integration test for a Spark pipeline that reads JSON data, filters records with age > 30, and writes the result. Which approach best ensures your test is reliable and fast?
hard
A. Use a small in-memory DataFrame with sample JSON data and compare output DataFrame to expected results
B. Run the full pipeline on the entire production dataset every time
C. Manually check output files after running the pipeline
D. Skip testing and fix bugs after deployment

Solution

  1. Step 1: Consider test data size and speed

    Using a small in-memory DataFrame makes tests fast and easy to run repeatedly.
  2. Step 2: Compare actual vs expected outputs

    Comparing DataFrames programmatically ensures correctness without manual checks.
  3. Step 3: Avoid full production runs or skipping tests

    Running full production data is slow; skipping tests risks bugs in production.
  4. Final Answer:

    Use a small in-memory DataFrame with sample JSON data and compare output DataFrame to expected results -> Option A
  5. Quick Check:

    Small sample data + compare outputs = reliable fast tests [OK]
Hint: Test small samples and compare outputs, not full data [OK]
Common Mistakes:
  • Testing on full production data every time
  • Manual output verification
  • Skipping tests before deployment
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard